/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.posplus.losspreventiondataimporter.importer;

import com.posplus.lossprevention.APDAOFactory;
import com.posplus.lossprevention.mapping.Cashiers;
import com.posplus.lossprevention.mapping.Stores;
import com.posplus.strack.mapping.Employees;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.posplus.losspreventiondataimporter.service.CashiersService;
import com.posplus.losspreventiondataimporter.service.EmployeeService;
import com.posplus.losspreventiondataimporter.service.StoresService;
import com.posplus.losspreventiondataimporter.util.ListToMap;
import org.apache.log4j.Logger;

/**
 *
 * @author scottw
 */
public class EmployeesImporter {
    private APDAOFactory lpFactory;
    private EmployeeService employeeService;
    private String storeCode;
    
    public EmployeesImporter(EmployeeService employeeService, APDAOFactory lpFactory){
        this.lpFactory = lpFactory;
        this.employeeService = employeeService;
    }
    
    public void dataImport(){
        List<Employees> employees = employeeService.getAll();
        mapAndPersist(employees, lpFactory);
    }
    
    private void mapAndPersist(List<Employees> employees, APDAOFactory lpFactory){
        List<Cashiers> mappedCashiers = new ArrayList<Cashiers>();
        StoresService storeService = new StoresService(lpFactory);
        Map<String, Stores> stores = ListToMap.storesToMap(storeService.getAll());
        
        Iterator<Employees> iter = employees.iterator();
        while (iter.hasNext()) {
            Employees next = iter.next();
            
            try{
                Stores store = stores.get(storeCode);
                if(store == null)
                    throw new RuntimeException("Store " + storeCode + " not found");
                Cashiers cashier = new Cashiers(store, "" + next.getEmpNo(), next.getFirstName(), next.getLastName(), next.getJobTitle(), null, null, null);
                mappedCashiers.add(cashier);
            }catch(RuntimeException ex){
                Logger.getLogger(EmployeesImporter.class).debug(ex);
            }
        }
        
        if(mappedCashiers.size() > 0){
            CashiersService cashierService = new CashiersService(lpFactory);
            //cashierService.bulkInsert(mappedCashiers);
	    cashierService.saveAll(mappedCashiers);
        }       
    }
    
    public void setStoreCode(String code){
        this.storeCode = code;
    }
    
    public String getStoreCode(){
        return storeCode;
    }
}
